package restyhttp

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	uuid "github.com/satori/go.uuid"
	"github.com/sirupsen/logrus"
	"gopkg.in/resty.v1"
	"time"
)
const defaultTimeout = 10 * time.Second

// 请求体日志
type httpRequestLogInfo struct {
	LogType    string
	ReqID      string
	TraceID    string
	Method     string
	URL        string
	QueryParam string
	Body       interface{}
	HOST       string
	SendAt     time.Time
}

// 返回体日志
type httpResponseLogInfo struct {
	LogType    string
	ReqID      string
	TraceID    string
	URL        string
	ReqDetail  *httpRequestLogInfo
	Method     string
	StatusCode int
	ReqSpent   time.Duration
	ResBody    string
}

//http请求日志
func clientHttpMiddleAfter(client *resty.Client, resp *resty.Response) error {
	var reqID string
	reqIDS, exist := resp.Request.QueryParam["req_id"]
	if exist {
		reqID = reqIDS[0]
	} else {
		reqID = ""
	}

	queryString := fmt.Sprintf("%v", resp.Request.QueryParam)
	reqDetail := &httpRequestLogInfo{
		URL:        resp.Request.URL,
		QueryParam: queryString,
		Method:     resp.Request.Method,
		Body:       resp.Request.Body,
		SendAt:     time.Now(),
		ReqID:      reqID,
	}

	logInfo := &httpResponseLogInfo{
		LogType:    "res",
		ReqID:      reqID,
		URL:        resp.Request.URL,
		ReqDetail:  reqDetail,
		Method:     resp.Request.Method,
		StatusCode: resp.RawResponse.StatusCode,
		ReqSpent:   resp.Time(),
		ResBody:    resp.String(),
	}

	client.SetTimeout(defaultTimeout)
	jsonData, err := jsoniter.MarshalToString(logInfo)
	if err != nil {
		return err
	}
	logrus.Info(jsonData)
	return nil
}

//http请求前
func clientBeforeRequestMiddleware(c *resty.Client, req *resty.Request) error  {
	reqID := uuid.NewV4().String()
	req.SetQueryParam("req_id", reqID)
	// 记录请求日志
	queryString := fmt.Sprintf("%v", req.QueryParam)
	logInfo := &httpRequestLogInfo{
		LogType:    "req",
		URL:        req.URL,
		QueryParam: queryString,
		Method:     req.Method,
		Body:       req.Body,
		SendAt:     time.Now(),
		ReqID:      reqID,
	}
	c.SetTimeout(defaultTimeout)

	jsonData, err := jsoniter.MarshalToString(logInfo)
	if err != nil {
		return err
	}
	logrus.Info(jsonData)
	return nil
}
